 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.interceptor;

 import cn.hutool.json.JSONUtil;
 import cn.hutool.jwt.JWT;
 import cn.hutool.jwt.JWTUtil;
 import cn.shun.exception.BizException;
 import cn.shun.local.LocalUserThreadLocal;
 import cn.shun.model.LocalUser;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.ModelAndView;

 /**
  * <p>Project: sboot_2023-cn.shun.interceptor-AuthInterceptor
  * <p>Powered by yishun On 2023-04-12 17:05:57
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @Slf4j
 public class AuthInterceptor implements HandlerInterceptor {

     private String tokenKey;

     public AuthInterceptor(String tokenKey) {
         this.tokenKey = tokenKey;
     }

     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         String token = request.getHeader("Authorization");
         String uri = request.getRequestURI();
         log.debug(uri);
         if (token != null) {
             boolean b = false;
             try {
                 b = JWTUtil.verify(token, tokenKey.getBytes());
             } catch (Exception ex) {

             }
             if (!b) {
                 throw new BizException(1003, "非法token或者token已过期");
             }
             log.debug("验证通过，继续执行");
             JWT jwt = JWTUtil.parseToken(token);
             LocalUser localUser = JSONUtil.toBean(jwt.getPayload().toString(), LocalUser.class);
             LocalUserThreadLocal.set(localUser);
             return true;
         }
         log.debug("验证失败~");
         return false;
     }

     @Override
     public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

     }

     @Override
     public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         log.debug("***************************接口调用结束， 从ThreadLocal删除用户信息***************************");
         LocalUserThreadLocal.clean();

     }
 }
